package com.gzhryc.net_marketing.cloud.goods.services;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.cloud.MarketConstants;
import com.gzhryc.net_marketing.core.enums.EGoodsState;
import com.gzhryc.net_marketing.cloud.goods.dao.CloudGoodsDao;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoods;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsAuditApply;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsSpace;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsSpaceAuditItem;
import com.gzhryc.net_marketing.cloud.goods.services.dto.CloudGoodsSearch;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CloudGoodsService {

    static Logger log = Logger.getLogger(CloudGoodsService.class);

    public static CloudGoodsService self() {
        return MultiDBTools.getService(MarketConstants.JDBC_KEY,CloudGoodsService.class, true);
    }

    CloudGoodsDao dao;

    public CloudGoodsService(String jdbcKey) {
        this.dao = new CloudGoodsDao(jdbcKey);
    }

    public List<CloudGoods> findBySearch(CloudGoodsSearch search, Integer pageNo, Integer pageLimit){
        Conditions condition = dao.buildConditions(search);
        condition.and().ge("payMoney",search.getMinPayMoney());
        condition.and().le("payMoney",search.getMaxPayMoney());
        condition.asc("priority");
        condition.desc("createDate");
        try {
            return dao.findByCondition(condition, pageNo, pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countBySearch(CloudGoodsSearch search){
        Conditions condition = dao.buildConditions(search);
        condition.and().ge("payMoney",search.getMinPayMoney());
        condition.and().le("payMoney",search.getMaxPayMoney());
        try {
            return dao.count(condition);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public CloudGoods getById(String id){
        if(StringTools.isNotBlank(id)){
            try {
                return dao.getById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public CloudGoods save(CloudGoodsAuditApply applyEntity,List<CloudGoodsSpaceAuditItem> spaceAuditItemList) throws LogicException {
        String goodsId = "G" + applyEntity.getSupplierId() + applyEntity.getGoodsId();
        CloudGoods goods = this.getById(goodsId);
        if(goods != null){
            if(EGoodsState.Delete.index().equals(goods.getState())){
                this.deleteById(goods.getId());
            }else{
                throw new LogicException("商品已存在");
            }
        }
        return add(applyEntity,spaceAuditItemList);
    }

    public CloudGoods add(CloudGoodsAuditApply applyEntity,List<CloudGoodsSpaceAuditItem> spaceAuditItemList) throws LogicException {
        CloudGoods goods = ClassTools.copy(new CloudGoods(),applyEntity);
        goods.setState(EGoodsState.OffTheShelf.index());
        String goodsId = "G" + goods.getSupplierId() + applyEntity.getGoodsId();
        goods.setId(goodsId);
        goods.setCreateDate(new Date());
        if(goods.getPriority() == null){
            goods.setPriority(10);
        }
        List<CloudGoodsSpace> goodsSpaceList = null;
        //保存规格参数
        if(spaceAuditItemList != null && spaceAuditItemList.size() > 0){
            goodsSpaceList = new ArrayList<>();
            for(CloudGoodsSpaceAuditItem auditItem : spaceAuditItemList){
                CloudGoodsSpace goodsSpace = ClassTools.copy(new CloudGoodsSpace(),auditItem,"goodsId");
                goodsSpace.setGoodsId(goods.getId());
                if(goodsSpace.getState() == null) {
                    goodsSpace.setState(EGoodsState.OffTheShelf.index());   //默认下架
                }
                goodsSpaceList.add(goodsSpace);
            }
        }
        JdbcSession.begin();
        try {
            if(dao.insert(goods) > 0){
                boolean flag = true;
                if(goodsSpaceList != null && goodsSpaceList.size() > 0){
                    flag = CloudGoodsSpaceService.self().add(goodsSpaceList);
                }
                if(flag){
                    JdbcSession.commit();
                    return goods;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.end();
        }
        return null;
    }

    public boolean updateNotNull(CloudGoods goods) throws LogicException {
        if(StringTools.isNotBlank(goods.getId())) {
            try {
                return dao.updateNotNull(goods) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

    public boolean downGoods(String code) throws LogicException{
        CloudGoods goods = getById(code);
        if(goods == null){
            throw new LogicException("未找到商品信息");
        }

        if(EGoodsState.OffTheShelf.index().equals(goods.getState())){
            throw new LogicException("商品已下架");
        }

        boolean flag = false;

        CloudGoods updateEntity = new CloudGoods();
        updateEntity.setId(code);
        updateEntity.setState(EGoodsState.OffTheShelf.index());

        try {
            if(dao.updateNotNull(updateEntity) > 0){
                flag = true;
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }

        if(flag){
            //找到该商品关联的商城，全部下架通知
            //NetworkMarketGoodsService.self().downGoods(code);
            return true;
        }
        return false;
    }

    /**
     * 逻辑删除
     * @param goods
     * @return
     */
    public boolean logicDelete(CloudGoods goods) throws LogicException {
        if(goods != null){
            CloudGoods updateEntity = new CloudGoods();
            updateEntity.setId(goods.getId());
            updateEntity.setState(EGoodsState.Delete.index());

            JdbcSession.begin();
            try {
                if(dao.updateNotNull(updateEntity) > 0){
                	JdbcSession.commit();
                    return true;
                }
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }finally {
                JdbcSession.end();
            }
        }
        return false;
    }

    public boolean deleteById(String id) throws LogicException{
        if(StringTools.isNotBlank(id)){
            boolean flag = false;
            JdbcSession.begin();
            try {
                if(dao.deleteById(id) > 0){
                    if(CloudGoodsSpaceService.self().deleteByGoodsId(id)) {
                    	JdbcSession.commit();
                        flag = true;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }finally {
                JdbcSession.end();
            }

            if(flag){
                try {
                    CloudGoodsAuditApplyService.self().closeAuditByGoodsCode(id);
                }catch (LogicException e){
                    log.error(e.getMessage(),e);
                }
                return true;
            }
        }
        return false;
    }
}
